package win.devhu.testing.simple.jsoupdemo

import com.alibaba.fastjson.JSON
import org.jsoup.Jsoup

fun main(args: Array<String>){
    val avicksUrl = "https://www.avicks.com/invest.html" //金世通
    val gomegoldUrl = "https://www.gomegold.com/" //国美黄金
    val gbankeUrl = "https://m.g-banker.com/GBankerWebApp/info/price?queryFlag=3"  //黄金钱包

    val avicksPrice = getGoldPrice(avicksUrl,"dd b")  //获取金世通实时金价
    val gomegoldPrice = getGoldPrice(gomegoldUrl,"#qupricea") //获取国美黄金实时金价
    val gbankePrice = getGbankePrice(gbankeUrl)   //获取黄金钱包实时金价

    println("------ 实时金价 ------")
    println("金世通: ${avicksPrice}\n国美黄金: ${gomegoldPrice}\n黄金钱包：${gbankePrice}")
    println("------ 实时金价 ------")
}

//通过页面爬取，使用css选择器
fun getGoldPrice(pageUrl:String,cssQuery:String): String {
    val doc = Jsoup.connect(pageUrl).get()
    val price  = doc.select("$cssQuery")
    return price.text()
}
//获取黄金钱包实时金价,JSON文件特殊处理
fun getGbankePrice(pageUrl:String): String {
    val doc = Jsoup.connect(pageUrl).ignoreContentType(true).execute()  //请求JSON
    val jobj = JSON.parseObject(doc.body())
    val price = jobj["realtime_price"].toString().toFloat()/100
    return price.toString()
}
